package com.zbj.consul.consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * ConsulConsumerController
 *
 * @author weigang
 * @create 2019-08-10
 **/
@RestController
@RequestMapping("/consul/consumer")
public class ConsulConsumerController {

    @Autowired
    private HelloService helloService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/hello")
    public String hello(@RequestParam(defaultValue = "world", required = false) String world) {
        return helloService.hello(world);
    }

    @GetMapping("/hello2")
    public String hello2(@RequestParam(defaultValue = "world", required = false) String world) {
        return restTemplate.getForObject("http://consul-provider/consul/provider/hello?world=" + world, String.class);
    }

    /**
     * 获取所有服务
     *
     * @return
     */
    @GetMapping("/services")
    public Object services() {
        return discoveryClient.getInstances("consul-provider");
    }

    /**
     * 从所有服务中选择一个服务（轮询）
     */
    @GetMapping("/discover")
    public Object discover() {
        // 不能调用 choose() 返回null 原因-> 提供者pom.xml需要依赖actuator
        return loadBalancerClient.choose("consul-provider").getUri().toString();
    }

}